import axios from 'axios'
import { LoadingObj } from '@/components/Loading'
import { Toast } from '@/components/Toast'
import router from 'vue-router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 15000
})

request.interceptors.request.use(
  config => {
    LoadingObj.open()
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  res => {
    setTimeout(() => {
      LoadingObj.hide()
    }, 600)
    if (res && res.status === 200) {
      const data = res.data
      if (data.code === 200) {
        return data
      } else if (data.code === 301) {
        Toast({
          text: '未登录或登录态失效，请登录',
          type: 'error'
        })
        sessionStorage.removeItem('user')
        router.push('/login')
        return {}
      } else {
        Toast({
          text: '请求出错',
          type: 'error'
        })
      }
    } else {
      Toast({
        text: '请求出错',
        type: 'error'
      })
    }
  },
  err => {
    return Promise.reject(err)
  }
)

export default request
